<?php

namespace support\Service;

use support\Model\UserRoleModel;

class UserRoleService
{

    public static function deleteUserRole($user_id)
    {
        $model = new UserRoleModel();
        return $model->delByWhere([["user_id", '=', $user_id]]);
    }

    /**
     * 批量插入用户角色关系
     * @param $userId 用户ID
     * @param $roleIds 角色ID集合
     * @since 2020/11/19
     */
    public static function insertUserRole($user_id, $roleIds)
    {
        $model = new UserRoleModel();
        if (!$roleIds) return [];
        $list = [];
        foreach ($roleIds as $val) {
            $data = [
                'user_id' => $user_id,
                'role_id' => $val,
            ];
            $list[] = $data;
        }
        return $model->insertBatch($list);

    }

    /**
     * 获取用户角色列表
     * @param $userId 用户ID
     * @return mixed
     * @since 2020/11/19
     */
    public static function getUserRoleList($user_id)
    {
        $model = new UserRoleModel();
        $roleList = $model
            ->select(['role.*'])
            ->join('role', $model->getTable() . '.role_id', '=', 'role.id')
            ->distinct(true)
            ->where($model->getTable() . '.user_id', '=', $user_id)
            ->where('role.status', '=', 1)
            ->where('role.mark', '=', 1)
            ->orderBy('role.sort')
            ->get()->toArray();
        return $roleList;
    }
}
